﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Web;

namespace NGM.MicrosoftConnect {
    public class AuthorizationRequest {
        public string ClientId { get; internal set; }
        public Display Display { get; internal set; }
        public CultureInfo Locale { get; internal set; }
        public Uri RedirectUri { get; internal set; }
        public ResponseType ResponseType { get; internal set; }
        public List<Scope> Scopes { get; internal set; }
        public string State { get; internal set; }

        public Uri GenerateRequestUri() {
            UriBuilder builder = new UriBuilder(MicrosoftConnectConstants.LiveOAuthPointer + "authorize");
            AppendParameter(builder, "client_id", this.ClientId);
            AppendParameter(builder, "display", this.Display.ToString().ToLowerInvariant());
            
            if (Locale != null)
                AppendParameter(builder, "locale", this.Locale.Name);

            AppendParameter(builder, "redirect_uri", this.RedirectUri.ToString());
            AppendParameter(builder, "response_type", this.ResponseType.ToString().ToLowerInvariant());
            AppendParameter(builder, "scope", this.GenerateFormattedScopeString());
            AppendParameter(builder, "state", this.State);

            return builder.Uri;
        }

        private void AppendParameter(UriBuilder uriBuilder, string paramName, string paramValue) {
            if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
                uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + paramName + "=" + HttpUtility.UrlEncode(paramValue);
            else
                uriBuilder.Query = paramName + "=" + HttpUtility.UrlEncode(paramValue); 
        }

        private string GenerateFormattedScopeString() {
            var stringBuilder = new StringBuilder();
            foreach (var extendedPermission in this.Scopes) {
                stringBuilder.AppendFormat("{0},", extendedPermission);
            }
            stringBuilder.Remove(stringBuilder.Length - 1, 1);
            return stringBuilder.ToString();
        }
    }
}